<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 微信交互类
 */ 
namespace app\home\controller;
use app\home\logic\WechatLogic;
use app\home\logic\UsersLogic;
class Weixin extends Base {
    public $client;
    public $wechat_config;
    public $dltoken;
    public $Wechat;
    public function _initialize(){
        parent::_initialize();
        //获取微信配置信息
        /*鼎联dltoken 区分多公众号唯一标识*/
        if(!$_GET["dltoken"]){
            $this->error('dltoken参数缺失');
        }else{
            $this->dltoken=$_GET["dltoken"];
        }
        $this->wechat_config = M('wx_user')->where(array('appid'=>$this->dltoken))->find();
        
        $options = array(
 			'token'=>$this->wechat_config['w_token'], //填写你设定的key
 			'encodingaeskey'=>$this->wechat_config['aeskey'], //填写加密用的EncodingAESKey
 			'appid'=>$this->wechat_config['appid'], //填写高级调用功能的app id
 			'appsecret'=>$this->wechat_config['appsecret'], //填写高级调用功能的密钥
        	);
        //$_SESSION['dltoken']='hahha';
    }
    
    public function oauth(){

    }
    
    public function index(){
        if($this->wechat_config['wait_access'] == 0)        
            exit($_GET["echostr"]);
        else        
            $this->responseMsg();
    } 
   
    
    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
	 if(empty($postStr))
        	exit("");
         
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $ev = $postObj->Event;
                $time = time();
                
                //点击菜单拉取消息时的事件推送 
                /*
                 * 1、click：点击推事件
                 * 用户点击click类型按钮后，微信服务器会通过消息接口推送消息类型为event的结构给开发者（参考消息接口指南）
                 * 并且带上按钮中开发者填写的key值，开发者可以通过自定义的key值与用户进行交互；
                 */
                if($postObj->MsgType == 'event' && $postObj->Event == 'CLICK')
                {
                    $keyword = trim($postObj->EventKey);
                }

                //如果是扫描定制二维码
                if($ev=='SCAN'){
                   /* $scean_id=$postObj->EventKey;
                    $datas['scene_id']=(int)$scean_id;
                    $where['openid']=(string)$fromUsername;
                    $datas['subscribe']=1;
                    $userid=M('users')->where($where)->find();
                    if(!$userid){
                        $datas['openid']=$where['openid'];
                        $res=M('users')->add($datas);
                    }
                    exit();*/
                   
                }
                if($ev=='unsubscribe'){
                  $where['openid']=(string)$fromUsername;
                  $data['subscribe']=0;
                  M('users')->where($where)->save($data);
                  exit();
                }
                
                if($ev=='subscribe'){
                    /*写入微信用户信息到表*/
                    $Wechat = new WechatLogic(); 
                    $Wechat->set_config($this->wechat_config);  
                    $userinfo= $Wechat->getUserInfo($fromUsername);
                    $userinfo['appid']=$this->wechat_config['appid'];//写入用户对应appid
                    $userinfo['scene_id']=str_replace('qrscene_', '', $postObj->EventKey);//扫店铺二维码写入店铺id
                    $UsersLogic = new UsersLogic(); 
                    $res=$UsersLogic->save_userdata($userinfo);

                    /*回复关注提示消息*/
                    $keyword="关注回复";
                }
                if($ev=='LOCATION'){
                    $record_member = tpCache("shop_info.record_member");
                    $latitude=$postObj->Latitude;//地理位置纬度
                    $longitude=$postObj->Longitude;//地理位置经度
                    $precision=$postObj->Precision;//地理位置精度

                    $clocation=getgps($latitude, $longitude,true);//将微信gps坐标转换成百度坐标
                    //$adress =gpslocation_city($clocation[0],$clocation[1]);//通过百度坐标获取地名
                 
                    //解析会员定位信息
                    $locadata['openid']=(string)$fromUsername;
                    $locadata['last_location'] =$clocation[0].','.$clocation[1];
                    $locadata['last_time']=time();
                    $locadata['reg_time']=time();
                    $users= M('users')->where('openid',(string)$fromUsername)->find();
                    if($users['relevance_id']){
                        $user_id=$users['relevance_id'];
                    }else{
                        $user_id=$users['user_id'];
                    }
                    $res=M('users_location')->where('user_id',$user_id)->find();

                    if($res){
                        M('users_location')->where('user_id',$user_id)->save($locadata);
                    }else{
                        $locadata['user_id']=$user_id;
                        M('users_location')->add($locadata);
                    }
                    $locadata['user_id']=$user_id;
                    if($record_member==1){
                        M('users_track')->add($locadata);//插入用户位置记录
                    }
                   /* $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";  

                    $msgType = "text";
                    $contentStr ='nihao';
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;*/
                 
                    exit();             
                }
                if(empty($keyword))
                    exit("Input something...");
                
                // 图文回复
               // $where['keyword']=array('like','%$keyword%');
               // $where['appid']=$this->wechat_config['appid'];
                $wx_img = M('wx_img')->where("keyword", "like", "%$keyword%")->find();
                if($wx_img)
                {
                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <ArticleCount><![CDATA[%s]]></ArticleCount>
                                <Articles>
                                    <item>
                                        <Title><![CDATA[%s]]></Title> 
                                        <Description><![CDATA[%s]]></Description>
                                        <PicUrl><![CDATA[%s]]></PicUrl>
                                        <Url><![CDATA[%s]]></Url>
                                    </item>                               
                                </Articles>
                                </xml>";                                        
                    $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,'news','1',$wx_img['title'],$wx_img['desc']
                            , $wx_img['pic'], $wx_img['url']);
                    exit($resultStr);                   
                }
                
                
                
                // 文本回复
                //$where['keyword']=array('like','%$keyword%');
                //$where['appid']=$this->wechat_config['appid'];
                $wx_text = M('wx_text')->where("keyword", "like", "%$keyword%")->find();
                if($wx_text)
                {
                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>";                    
                    $contentStr = $wx_text['text'];
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
                    exit($resultStr);    
                }

                // 其他文本回复                
                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <Content><![CDATA[%s]]></Content>
                                <FuncFlag>0</FuncFlag>
                                </xml>"; 
                            
                    $contentStr ='感谢您的留言，我们会尽快回复您！';
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, 'text', $contentStr);
                    exit($resultStr);                   
      
    }


}